<template>
    <el-row type="flex" justify="center" :gutter="6">
        <!--抄表框-->
        <el-col :xs="22" :sm="8" :md="8" :lg="8" :xl="10">
            <el-container class="grid-content bg-purple-dark">
                <el-header>
                    <el-row justify="left" :gutter="3">
                        <el-col :span="10">
                            <el-select v-model="current_building_id" filterable placeholder="选择宿舍楼"
                                       @change="buildingChanged">
                                <el-option
                                        v-for="building in buildings"
                                        :key="building.id"
                                        :label="building.name"
                                        :value="building.id">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="14"
                                style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;">
                            <el-button type="primary" icon="el-icon-arrow-left" style="width:10%;padding:12px 2px;"
                                       @click="prevDorm"></el-button>
                            <el-select v-model="current_dorm_id" filterable placeholder="选择宿舍" @change="dormChanged"
                                       style="width:70%">
                                <el-option
                                        v-for="dorm in dorms"
                                        :key="dorm.id"
                                        :label="dorm.code"
                                        :value="dorm.id">
                                </el-option>
                            </el-select>
                            <el-button type="primary" icon="el-icon-arrow-right" style="width:10%;padding:12px 2px;"
                                       @click="nextDorm"></el-button>
                        </el-col>
                    </el-row>
                </el-header>
                <el-container class="bg-purple-light">
                    <el-form :model="formRec" :rules="rules" ref="formRec" label-width="150px">
                        <el-form-item>
                            <el-button type="success" @click="toPrevRec" :disabled="formRec.prev_record_id==null">上一条
                            </el-button>
                            <el-button type="primary" :disabled='current_dorm_id==null' @click="onSubmit">
                                {{formRec.id==null?'保存':'更新'}}
                            </el-button>
                        </el-form-item>
                        <el-form-item label="本抄表隶属周期" required>
                            <el-select v-model="formRec.period_id" style="width:90%">
                                <el-option v-for="period in history_period" :label="period.name" :value="period.id"
                                           :key="period.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="抄表日期" prop="record_date">
                            <el-date-picker v-model="formRec.record_date" type="date" placeholder="选择日期"
                                            value-format="yyyy-MM-dd" :picker-options="pickerOptions" style="width:90%">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="电表读数" prop="electric_reading">
                            <el-input-number v-model="formRec.electric_reading" :precision="2" :step="0.1"
                                             :min="0" style="width:90%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="水表读数" prop="water_reading">
                            <el-input-number v-model="formRec.water_reading" :precision="2" :step="0.1"
                                             :min="0" style="width:90%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="上次抄表日期" prop="prev_record_date">
                        <el-date-picker v-model="formRec.prev_record_date" type="date" placeholder="选择日期"
                                        value-format="yyyy-MM-dd" :picker-options="pickerOptions"
                                        :disabled="formRec.prev_record_id!=null" style="width:90%">
                        </el-date-picker>
                        </el-form-item>
                        <el-form-item label="上次电表读数" prop="electric_prev_reading">
                            <el-input-number v-model="formRec.electric_prev_reading" :precision="2" :step="0.1"
                                             :disabled="formRec.prev_record_id!=null" :min="0"
                                             style="width:90%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="上次水表读数" prop="water_prev_reading">
                            <el-input-number v-model="formRec.water_prev_reading" :precision="2" :step="0.1"
                                             :disabled="formRec.prev_record_id!=null" :min="0"
                                             style="width:90%"></el-input-number>
                        </el-form-item>

                        <el-form-item label="备注">
                            <el-input v-model="formRec.remark" placeholder="备注信息" style="width:90%"></el-input>
                        </el-form-item>

                    </el-form>
                </el-container>
            </el-container>
        </el-col>
        <!--人员查找-->
        <el-col :xs="0" :sm="8" :md="8" :lg="8" :xl="6">
            <el-container class="grid-content bg-purple-dark">
                <el-header style="text-align: right; font-size: 15px">
                    <el-row type="flex" justify="end">
                        <el-col :xs="24" :sm="22" :md="12" :lg="12" :xl="12">
                            <el-input
                                    v-model="search"
                                    size="medium"
                                    prefix-icon="el-icon-search"
                                    placeholder="输入姓名关键字搜索"
                            />
                        </el-col>
                    </el-row>
                </el-header>
                <div style="height: 76vh;width: 100%;padding:5px">
                    <el-table
                            :data="staffFound"
                            height="74vh"
                            style="width: 100%">
                        <el-table-column
                                align="center"
                                prop="name"
                                label="姓名"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="id_card"
                                label="身份证">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                label="操作">
                            <template slot-scope="scope">
                                <a :href="'/staff#/staff_list/'+scope.row.department_id">查看</a>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-container>
        </el-col>
        <!--阶梯价格-->
        <el-col :xs="0" :sm="8" :md="8" :lg="8" :xl="6">
            <el-container class="grid-content bg-purple-light el-container" direction="vertical">
                <el-form label-width="100px" :inline="true">
                    <el-form-item label="基本水价">
                        <el-input-number :precision="2" :min="0" :step="0.1" :max="10"
                                         v-model="waterMeterInfo.unit_price" class="inputNum"></el-input-number>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="upateUnitPrice(waterMeterInfo)">更新</el-button>
                    </el-form-item>
                </el-form>
                <div style="height: 200px;width: 100%;padding:5px">
                    <el-table
                            :data="waterMeterInfo.meter_type_price_levels"
                            height="180"
                            style="width: 100%">
                        <el-table-column
                                align="center"
                                prop="level_value"
                                label="阶梯价下限"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="level_price"
                                label="阶梯价"
                                width="120">
                        </el-table-column>
                        <el-table-column align="right">
                            <template slot="header" slot-scope="scope">
                                <el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
                                           @click="handleAdd(waterMeterInfo)"></el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        @click="handleEdit(scope.$index, scope.row,waterMeterInfo)">更新
                                </el-button>
                                <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDelete(scope.$index, scope.row)">刪除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <hr style="width: 96%; height: 1px; border: none; background-color: #282828"/>
                <el-form label-width="100px" :inline="true">
                    <el-form-item label="基本电价">
                        <el-input-number :precision="2" :min="0" :step="0.1" :max="10"
                                         v-model="electricMeterInfo.unit_price" class="inputNum"></el-input-number>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updateUnitPrice(electricMeterInfo)">更新</el-button>
                    </el-form-item>
                </el-form>
                <div style="height: 200px;width: 100%;padding:5px">
                    <el-table
                            :data="electricMeterInfo.meter_type_price_levels"
                            height="180"
                            style="width: 100%">
                        <el-table-column
                                align="center"
                                prop="level_value"
                                label="阶梯价下限"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="level_price"
                                label="阶梯价"
                                width="120">
                        </el-table-column>
                        <el-table-column align="right">
                            <template slot="header" slot-scope="scope">
                                <el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
                                           @click="handleAdd(electricMeterInfo)"></el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        @click="handleEdit(scope.$index, scope.row,electricMeterInfo)">更新
                                </el-button>
                                <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDelete(scope.$index, scope.row)">刪除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-container>
        </el-col>
        <el-dialog :title="oprtName+'阶梯'+meterType+'价'" :visible.sync="dialogFormVisible" width="40%">
            <el-form :model="formPriceLevel" ref="formPriceLevel">
                <el-form-item label="阶梯用量" prop="level_value">
                    <el-input-number v-model="formPriceLevel.level_value" :min="0" :precision="2"
                                     class="inputNum"></el-input-number>
                </el-form-item>
                <el-form-item label="阶梯价格" prop="level_price">
                    <el-input-number v-model="formPriceLevel.level_price" :precision="2" class="inputNum"
                                     :step="0.1"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleOprt">{{oprtName}}</el-button>
            </div>
        </el-dialog>

    </el-row>
</template>
<style>
    .el-col {
        border-radius: 4px;
    }

    .el-container {
        padding-top: 10px;
    }

    .bg-purple-dark {
        background: #99a9bf;
    }

    .bg-purple {
        background: #d3dce6;
    }

    .bg-purple-light {
        background: #e5e9f2;
    }

    .grid-content {
        border-radius: 6px;
        min-height: 80vh;
    }

    .inputNum {
        font-family: Arial, Verdana, Sans-serif;
    }

    .datepicker-wd {
        width: 60px;
    }
</style>
<script>
    export default{
        data(){
            var checkWaterRec = (rule, value, callback) => {
                if (this.formRec.change_water_meter == false) {
                    if (value < this.formRec.water_prev_reading) {
                        return callback(new Error('读数不能小于等于上一次抄表'));
                    } else {
                        return callback();
                    }
                } else {
                    return callback();
                }
            };
            var checkEletricRec = (rule, value, callback) => {
                if (this.formRec.change_electric_meter == false) {
                    if (value < this.formRec.electric_prev_reading) {
                        return callback(new Error('读数不能小于等于上一次抄表'));
                    } else {
                        return callback();
                    }
                } else {
                    return callback();
                }
            };
            var checkPeriod = (rule, value, callback) => {
                var selected_period = this.history_period.find(function (p) {
                    return p.id == this.formRec.period_id;
                }, this);
                const start_date = new Date(selected_period.start_date);
                const end_date = new Date(selected_period.end_date);
                const prev_record_date = new Date(this.formRec.prev_record_date);
                const record_date = new Date(this.formRec.record_date);
                if (prev_record_date >= start_date && prev_record_date < end_date) {
                    return callback();
                } else if (prev_record_date < start_date && record_date > start_date) {
                    return callback();
                } else {
                    return callback(new Error('与隶属周期起始时间不匹配'));
                }

            };
            var checkDate = (rule, value, callback) => {
                if (new Date(value) > new Date()) {
                    return callback(new Error('抄表日期不能大于今天'));
                } else if (new Date(this.formRec.record_date) < new Date(this.formRec.prev_record_date)) {
                    return callback(new Error('抄表日期必须大于等于上次抄表日期'));
                } else {
                    return callback();
                }
            };
            return {
                curDormIdx: 0,
                dialogFormVisible: false,
                formPriceLevel: {
                    id: null,
                    unit_price: '',
                },
                formPriceLevel: {
                    id: null,
                    meter_type_id: '',
                    level_value: '',
                    level_price: ''
                },
                oprtName: '',
                meterType: '',
                search: '',
                buildings: [],
                current_building_id: '',
                current_dorm_id: null,
                dorms: [],
                history_period: [],
                staffFound: [],
                waterMeterInfo: {},
                electricMeterInfo: {},
                formRec: {
                    id: null,
                    period_id: '',
                    dorm_id: '',
                    prev_record_id: null,
                    electric_prev_reading: '',
                    electric_reading: '',
                    water_prev_reading: '',
                    water_reading: '',
                    prev_record_date: '',
                    record_date: '',
                    change_water_meter: false,
                    change_electric_meter: false,
                    remark: ''
                },
                rules: {
                    period_id: [
                        {required: true, message: '请选择隶属周期', trigger: 'change'},
                    ],
                    electric_prev_reading: [
                        {required: true, message: '请填写上次电表读数', trigger: 'change'}
                    ],
                    electric_reading: [
                        {required: true, message: '请填写电表读数', trigger: 'change'},
                        {validator: checkEletricRec, trigger: 'blur'}
                    ],
                    water_prev_reading: [
                        {required: true, message: '请填写上次水表读数', trigger: 'change'}
                    ],
                    water_reading: [
                        {required: true, message: '请填写水表读数', trigger: 'change'},
                        {validator: checkWaterRec, trigger: 'blur'}
                    ],
                    prev_record_date: [
                        {required: true, message: '请选择上次抄表日期', trigger: 'change'},
                        {validator: checkDate, trigger: 'blur'},
                        {validator: checkPeriod, trigger: 'blur'}
                    ],
                    record_date: [
                        {required: true, message: '请选择抄表日期', trigger: 'change'},
                        {validator: checkDate, trigger: 'blur'},
                        {validator: checkPeriod, trigger: 'blur'}
                    ],
                    electric_price: [
                        {required: true, message: '请填写电费', trigger: 'change'}
                    ],
                    water_price: [
                        {required: true, message: '请填写水费', trigger: 'change'}
                    ],
                },
                current_record_idx: 0,
                current_dorm: null,
                history_period: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '1号',
                        onClick(picker) {
                            const date = new Date();
                            date.setDate(1);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '上月1号',
                        onClick(picker) {
                            const date = new Date();
                            date.setMonth(date.getMonth() - 1);
                            date.setDate(1);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            }
        },
        methods: {
            toPrevRec(){
                axios.get('api/v1/dormMeterRecord/' + this.formRec.prev_record_id).then(result => {
                    this.formRec = _.cloneDeep(result.data);
                });
                this.current_record_idx++;
            },
            getBuildings(){
                axios.get('api/v1/building').then(result => {
                    if(result.data && result.data.length){
                        this.buildings = result.data;
                    }
                });
            },
            getPriceInfo(){
                axios.get('api/v1/meterType').then(rst => {
                    let meters = rst.data;
                    if(meters && meters.length){
                        let waterMeter = meters.find(v=>v.code==='water_meter');
                        if(waterMeter)this.waterMeterInfo = waterMeter;
                        let electricMeter = meters.find(v=>v.code==='electric_meter');
                        if(electricMeter)this.electricMeterInfo = electricMeter;
                    }
                }).catch(err => {
                    if (err.response) {
                        console.log(err.response);
                    }
                });
            },
            getPeriods(){
                var today = new Date().toISOString().slice(0, 10);
                this.formRec.record_date = today;
                axios.get('api/v1/period?log_date=' + today).then(result => {
                    this.history_period = result.data;
                    if (new Date().getDate() < 10) {
                        if (this.history_period.length > 1) {
                            this.formRec.period_id = this.history_period[1].id;
                        }
                    } else {
                        if (this.history_period.length > 0) {
                            this.formRec.period_id = this.history_period[0].id;
                        }
                    }
                }).catch(error => {
                    if (error.response) {
                        console.log(error.response);
                    }
                });
            },
            handleEdit(index, row, priceInfo){
                this.meterType = priceInfo.name.slice(0, 1);
                this.formPriceLevel = row;
                this.oprtName = '更新';
                this.dialogFormVisible = true;
            },
            handleOprt(){
                if (this.oprtName == '新增') {
                    axios.post('api/v1/meterTypePriceLevel', this.formPriceLevel).then(rst => {
                        this.$notify.success({message: '新增成功'});
                        this.getPriceInfo();
                        this.dialogFormVisible = false;
                    }).catch(err => {
                        if (err.response) {
                            console.log(err.response);
                        }
                        this.$notify.error({message: '新增失败'});
                    });
                } else {
                    axios.put('api/v1/meterTypePriceLevel/' + this.formPriceLevel.id, {
                        level_value: this.formPriceLevel.level_value,
                        level_price: this.formPriceLevel.level_price
                    })
                        .then(rst => {
                            this.$notify.success({message: '更新成功'});
                            this.getPriceInfo();
                            this.dialogFormVisible = false;
                        }).catch(err => {
                        if (err.response) {
                            console.log(err.response);
                        }
                        this.$notify.error({message: '更新失败'});
                    });
                }
            },
            handleDelete(index, row){
                this.$confirm('确定要删除此阶梯电价?', '删除提示').then(() => {
                    axios.delete('api/v1/meterTypePriceLevel/' + row.id).then(rst => {
                        this.$notify.success({message: '删除成功'});
                        this.getPriceInfo();
                    }).catch(err => {
                        if (err.response) {
                            console.log(err.response);
                        }
                        this.$notify.error({message: '删除失败'});
                    });
                }).catch(action => {
                    console.log(action)
                });
            },
            handleAdd(priceInfo){
                this.meterType = priceInfo.name.slice(0, 1);
                this.formPriceLevel.meter_type_id = priceInfo.id;
                if (this.$refs.formPriceLevel) {
                    this.$refs.formPriceLevel.resetFields();
                }
                this.oprtName = '新增';
                this.dialogFormVisible = true;
            },
            updateUnitPrice(priceInfo){
                axios.put('api/v1/meterType/' + priceInfo.id, {unit_price: priceInfo.unit_price}).then(rst => {
                    this.$notify.success({message: '更新成功'});
                }).catch(err => {
                    if (err.response) console.log(err.response);
                    this.$notify.error({message: '更新失败'});
                });
            },
            buildingChanged(){
                this.current_dorm_id = null;
                axios.get('api/v1/dorm?building=' + this.current_building_id).then(
                    result => {
                        this.dorms = result.data;
                        if (this.dorms && this.dorms.length > 0) {
                            this.current_dorm_id = this.dorms[0].id;
                        }
                    });
            },
            dormChanged(){
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                axios.get('api/v1/dormMeterRecord?dorm_id=' + this.current_dorm_id).then(result => {
                    var rec = result.data;
                    if (rec) {
                        this.formRec.prev_record_id = rec.id;
                        this.formRec.prev_record_date = rec.record_date;
                        this.formRec.water_prev_reading = rec.water_reading;
                        this.formRec.electric_prev_reading = rec.electric_reading;
                    } else {
                        this.formRec.prev_record_date = '';
                        this.formRec.water_prev_reading = '';
                        this.formRec.electric_prev_reading = '';
                    }
                    loading.close();
                });
                this.formRec.id = null;
                this.formRec.water_reading = '';
                this.formRec.electric_reading = '';

            },
            getStaff(search){
                axios.get('api/v1/staff?search=' + search).then(rst => {
                    console.log('search change to ' + this.search);
                    console.log(rst);
                    this.staffFound = rst.data;
                }).catch(err => {
                    if (err.response) {
                        console.log(err.response);
                    }
                });
            },
            onSubmit(){
                if (this.formRec.id == null) {
                    this.formRec.dorm_id = this.current_dorm_id;
                    this.$refs['formRec'].validate(result => {
                        if (result) {
                            axios.post('api/v1/dormMeterRecord', this.formRec).then(result => {
                                this.$notify({message: '录入成功', type: 'success'});
                                this.nextDorm();
                            }).catch(error => {
                                if (error.response) {
                                    console.log(error.response);
                                } else {
                                    console.log(error);
                                }

                                this.$notify.error({message: '录入失败'});
                            });
                        }
                    });
                } else {
                    this.$refs['formRec'].validate(result => {
                        if (result) {
                            axios.put('api/v1/dormMeterRecord/' + this.formRec.id, this.formRec).then(result => {
                                this.$notify({message: '更新成功', type: 'success'});
                            }).catch(error => {
                                console.log(error);
                                this.$notify.error({message: '更新失败'});
                            });
                        }
                    });
                }

            },
            prevDorm(){
                if (this.dorms) {
                    var curDormIdx = this.dorms.findIndex(function (d) {
                        return d.id == this.current_dorm_id;
                    }, this);
                    if (curDormIdx > 0) {
                        var prev = this.dorms[curDormIdx - 1];
                        this.current_dorm_id = prev.id;
                        this.dormChanged();
                    } else {
                        this.$notify.warning({message: '当前已经是第一个宿舍'});
                    }
                }else{
                    this.$notify.warning({message: '请先选择宿舍楼'});
                }
            },
            nextDorm(){
                if (this.dorms) {
                    var curDormIdx = this.dorms.findIndex(function (d) {
                        return d.id == this.current_dorm_id;
                    }, this);
                    if (curDormIdx < this.dorms.length-1) {
                        var next = this.dorms[curDormIdx + 1];
                        this.current_dorm_id = next.id;
                        this.dormChanged();
                    } else {
                        this.$notify.warning({message: '当前已经是最后一个宿舍'});
                    }
                }else{
                    this.$notify.warning({message: '请先选择宿舍楼'});
                }
            }
        },
        created(){
            this.getPriceInfo();
            this.getBuildings();
            this.getPeriods();
        },
        watch: {
            'search': function (to, from) {
                this.getStaff(to);
            }
        }
    }
</script>
